<template>
  <div id="firmware-manage">
    <div class="search-box">
      <Row type='flex' justify="space-between" align='bottom' style="padding:0 24px">
        <Col>
          <RadioGroup v-model="buttonValue" type="button" @on-change='changeBtn'>
            <Radio label="1">升级包列表</Radio>
            <Radio label="2">回退包列表</Radio>
          </RadioGroup>
        </Col>
        <Row type='flex' align='middle'>
          <Col class="search-item"><span>固件版本：</span><Input placeholder="请输入" v-model='inputValue' style="width:180px" :maxlength="4" :clearable='true' @on-keyup='keyUp' @on-clear='doSearch' /></Col>
          <Col class="search-item"><Button type="primary" class="draw-btn" @click="doSearch">查询</Button></Col>
          <Col class="search-item" v-if="buttonValue === '1'"><Button type="primary" @click="loadFirmware">上传固件包</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe :columns="columns" :data="buttonValue === '1'?updateTable:backTable" class="table-list" :height='getHeight' :loading='loading'>
      <template slot-scope="{ row, index }" slot="action">
        <span @click="delMaterial(row)"><i class="iconsys icondel" title="删除"></i></span>
      </template>
    </Table>
    <Row type='flex' justify="end" style="padding:20px">
      <Col>
        <Page :total="buttonValue === '1'?updateObj.total:bakcObj.total"
            :current="buttonValue === '1'?updateObj.pageIndex:bakcObj.pageIndex"
            :page-size="buttonValue === '1'?updateObj.pageSize:bakcObj.pageSize"
            show-sizer
            show-total
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <Modal title="确认提示"
             width='400' :transfer='false'
             v-model="delReason">
        <Form :model="delValidate"
              ref="delValidate"
              :label-width="50"
              :rules="delRule">
          <FormItem label="原因:"
                    prop="remark">
            <Input v-model="delValidate.remark"
                   style="width:300px;" :maxlength='100'
                   type="textarea"
                   :autosize="{minRows: 5,maxRows: 10}"
                   placeholder="请输入删除原因" />
                   <p style="text-align: right;width:300px">{{delValidate.remark.length}}/100</p>
          </FormItem>
        </Form>
        <div slot="footer"
             class="foot">
          <Button class="btn" style="margin-right:16px;width:72px"
                  @click='cancelDel'>取消</Button>
          <Button type="primary"
                  class="btn" style="width:72px"
                  @click="sureDel">确认</Button>
        </div>
      </Modal>
      <Drawer title="上传固件包" :closable="true" width='540' :transfer='false' v-model="openDraw" class="history-draw">
        <Row type='flex' justify="center" align='middle' style="margin-top:50px">
          <Col>
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
              <FormItem label="固件包：" prop="firwareName">
                <Row type='flex' align='middle'>
                  <Col>
                    <Upload ref="upload"
                    :format="['zip']"
                      :on-format-error="handleFormatError"
                      :data='uploadParmas'
                      :on-success="handleSuccess"
                      :on-error='handleErr'
                      type="drag"
                      :show-upload-list="false"
                      :action="$config.uploadUrl">
                      <Button type="primary" class="draw-btn">上传</Button>
                    </Upload>
                  </Col>
                  <Col><span style="margin: 0 12px">{{formValidate.firwareName}}</span><Icon type="ios-close-circle" size='18' v-if="formValidate.firwareName" @click="cancelLoad('1')" /></Col>
                </Row>
              </FormItem>
              <FormItem label="固件分类：" prop="firmwareType">
                <Input placeholder="固件分类类型" v-model='formValidate.firmwareType' style="width:260px" :disabled='true' />
              </FormItem>
              <FormItem label="固件版本：" prop="targetVersion">
                <Input placeholder="固件版本号" v-model='formValidate.targetVersion' style="width:260px" :disabled='true' />
              </FormItem>
              <FormItem label="起始版本：" prop="originVersion">
                <Input placeholder="起始版本号" v-model='formValidate.originVersion' style="width:260px" :disabled='true' />
              </FormItem>
            </Form>
          </Col>
        </Row>
        <div class="demo-drawer-footer">
          <Button style="margin-right: 20px" class="draw-btn" @click="cancelLoad('2')">取消</Button>
          <Button type="primary" class="draw-btn" @click="sureLoad" :disabled='isDisabled'>确定</Button>
        </div>
      </Drawer>
  </div>
</template>

<script>
import { getFirmwareManageList, loadFirmwarePackage, delFirmwareSingle } from '@/api/setting'
export default {
  name: 'global_setting_page_19',
  watch: {
    openDraw (val) {
      if (!val) {
        this.$refs.formValidate.resetFields()
      }
    },
    delReason (status) {
      if (!status) {
        this.$refs.delValidate.resetFields()
      }
    }
  },
  computed: {
    getHeight () {
      let height = 0
      if (this.buttonValue === '1') {
        height = this.updateTable.length > 10 ? 520 : 0
      } else {
        height = this.backTable.length > 10 ? 520 : 0
      }
      return height
    }
  },
  data () {
    return {
      uploadParmas: {
        project: 'material',
        type: 'firmware'
      }, // 上传固件的参数
      isDisabled: false,
      loading: true,
      deviceFimwareId: '',
      openDraw: false,
      delReason: false, // 删除原因状态
      delValidate: {
        remark: ''
      },
      delRule: {
        remark: { required: true, message: '删除原因不能为空', trigger: 'change' }
      },
      formValidate: {
        firwareName: '',
        firmwareType: '',
        originVersion: '',
        targetVersion: '',
        url: ''
      },
      ruleValidate: {
        firwareName: { required: true, message: '请上传固件', trigger: 'change' }
        // firmwareType: { message: '请上传固件', trigger: 'change' },
        // targetVersion: { required: true, message: '固件版本不能为空', trigger: 'change' },
        // originVersion: { required: true, message: '起始版本不能为空', trigger: 'change' }
      },
      updateObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      bakcObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      buttonValue: '1',
      inputValue: '', // 固件版本
      updateTable: [],
      backTable: [],
      columns: [
        {
          title: '固件包名称',
          key: 'firwareName'
        },
        {
          title: '固件版本',
          key: 'targetVersion'
        },
        {
          title: '起始版本',
          key: 'originVersion'
        },
        {
          title: '操作时间',
          key: 'createTime'
        },
        {
          title: '操作',
          slot: 'action',
          width: 120
        }
      ]
    }
  },
  methods: {
    keyUp () {
      // this.inputValue = this.inputValue.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
      this.inputValue = this.inputValue.replace(/[^\d]/g, '')
    },
    changeBtn (val) {
      this.buttonValue = val
      this.getData()
    },
    changePageIndex (index) {
      if (this.buttonValue === '1') {
        this.updateObj.pageIndex = index
      } else {
        this.bakcObj.pageIndex = index
      }
      this.getData()
    },
    changePageSize (size) {
      if (this.buttonValue === '1') {
        this.updateObj.pageSize = size
        this.updateObj.pageIndex = 1
      } else {
        this.bakcObj.pageSize = size
        this.bakcObj.pageIndex = 1
      }
      this.getData()
    },
    doSearch () {
      if (this.buttonValue === '1') {
        this.updateObj.pageIndex = 1
      } else {
        this.bakcObj.pageIndex = 1
      }
      this.getData()
    },
    delMaterial (row) {
      this.delReason = true
      this.deviceFimwareId = row.deviceFimwareId
    },
    cancelDel () {
      this.delReason = false
    },
    sureDel () {
      this.$refs.delValidate.validate((valid) => {
        if (valid) {
          delFirmwareSingle({
            deviceFimwareId: this.deviceFimwareId,
            remark: this.delValidate.remark
          }).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.$Message.success('删除成功！')
              this.delReason = false
              this.getData()
            } else {
              this.$Message.error(`${result.error}`)
            }
          })
        }
      })
    },
    loadFirmware () {
      this.openDraw = true
    },
    cancelLoad (type) {
      if (type === '1') {
        this.$refs.formValidate.resetFields()
      } else if (type === '2') {
        this.openDraw = false
      }
    },
    sureLoad () {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          this.isDisabled = true
          setTimeout(() => {
            loadFirmwarePackage({
              ...this.formValidate
            }).then(res => {
              this.isDisabled = false
              if (res.data.status === 200) {
                this.openDraw = false
                this.$Message.success('上传成功！')
                this.getData()
              } else {
                this.$Message.error({
                  content: `${res.data.error}`,
                  duration: 1
                })
              }
            })
          }, 600)
        }
      })
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '上传文件格式错误,仅支持zip格式',
        duration: 2
      })
    },
    handleErr () {
      this.$Message.error('上传失败！')
    },
    handleSuccess (response, file) {
      let name = file.name
      if (name.indexOf('_') !== -1) {
        if (name.split('_')[0].length === 4 && name.split('_')[1].split('.')[0].length === 4 && (/^[0-9]+$/.test(name.split('_')[0].substring(0, 3))) && (/^[0-9]+$/.test(name.split('_')[1].split('.')[0].substring(0, 3))) && name.split('_')[0] !== name.split('_')[1].split('.')[0]) {
          this.formValidate.firwareName = file.name
          this.formValidate.url = response.full_url
          this.formValidate.originVersion = name.split('_')[0]
          this.formValidate.targetVersion = name.split('_')[1].split('.')[0]
          if (this.formValidate.targetVersion > this.formValidate.originVersion) {
            this.formValidate.firmwareType = '升级'
          } else {
            this.formValidate.firmwareType = '回退'
          }
        } else {
          this.$Notice.warning({
            title: '上传文件名称格式错误',
            desc: '文件名称错误,应为YYYY_XXXX.zip',
            duration: 2
          })
        }
      } else {
        this.$Notice.warning({
          title: '上传文件名称格式错误',
          desc: '文件名称错误,应为YYYY_XXXX.zip',
          duration: 2
        })
      }
    },
    getData () {
      this.loading = true
      getFirmwareManageList({
        upgradeType: this.buttonValue,
        targetVersion: this.inputValue,
        offset: this.buttonValue === '1' ? this.updateObj.pageSize * (this.updateObj.pageIndex - 1) : this.bakcObj.pageSize * (this.bakcObj.pageIndex - 1),
        limit: this.buttonValue === '1' ? this.updateObj.pageSize : this.bakcObj.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          if (this.buttonValue === '1') {
            this.updateTable = result.data || []
            this.updateObj.total = result.totalCount || 0
            if (result.data.length / this.updateObj.pageSize === 0) {
              if (this.updateObj.pageIndex > 1) {
                this.updateObj.pageIndex--
                this.getData()
              }
            }
          } else {
            this.backTable = result.data || []
            this.bakcObj.total = result.totalCount || 0
            if (result.data.length / this.bakcObj.pageSize === 0) {
              if (this.bakcObj.pageIndex > 1) {
                this.bakcObj.pageIndex--
                this.getData()
              }
            }
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    }
  },
  mounted () {
    this.getData()
  }
}
</script>

<style lang='less'>
  #firmware-manage{
    /* .ivu-form-item {
      margin-bottom: 0;
    } */
    .ivu-radio-group-button .ivu-radio-wrapper-checked:first-child {
      color: #fff;
      background: #2d8cf0;
    }
    .ivu-radio-group-button .ivu-radio-wrapper-checked {
      color: #fff;
      background: #2d8cf0;
    }
    .demo-drawer-footer {
      width: 100%;
      position: absolute;
      bottom: 0;
      right: 0;
      border-top: 1px solid #e8e8e8;
      padding: 10px 16px;
      text-align: right;
      background: #fff;
    }
    .draw-btn {
      width: 80px;
    }
    .ivu-upload-drag {
      border: 0;
      text-align: left;
    }
  }
</style>
